﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.Text;

/// <summary>
///WebPay 的摘要说明
/// </summary>
public class WebPay
{
    /// <summary>
    /// 与ASP兼容的MD5加密算法
    /// </summary>
    /// 

    public static string GetMD5Sign(string str, string key)
    {
        byte[] b = System.Text.Encoding.Default.GetBytes(str);
        b = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(b);
        string ret = "";
        for (int i = 0; i < b.Length; i++)
        {
            ret += b[i].ToString("x").PadLeft(2, '0');
        }
        return ret;
    }
    public static string GetMD5(string s, string _input_charset)
    {
        MD5 md5 = new MD5CryptoServiceProvider();
        byte[] t = md5.ComputeHash(Encoding.GetEncoding(_input_charset).GetBytes(s));
        StringBuilder sb = new StringBuilder(32);
        for (int i = 0; i < t.Length; i++)
        {
            sb.Append(t[i].ToString("x").PadLeft(2, '0'));
        }
        return sb.ToString();
    }



    /// <summary>
    /// 冒泡排序法
    /// </summary>
    public static string[] BubbleSort(string[] r)
    {
        int i, j; //交换标志 
        string temp;

        bool exchange;

        for (i = 0; i < r.Length; i++) //最多做R.Length-1趟排序 
        {
            exchange = false; //本趟排序开始前，交换标志应为假

            for (j = r.Length - 2; j >= i; j--)
            {
                if (System.String.CompareOrdinal(r[j + 1], r[j]) < 0)　//交换条件
                {
                    temp = r[j + 1];
                    r[j + 1] = r[j];
                    r[j] = temp;

                    exchange = true; //发生了交换，故将交换标志置为真 
                }
            }

            if (!exchange) //本趟排序未发生交换，提前终止算法 
            {
                break;
            }
        }
        return r;
    }
    public static string NewUrl(
        string mer_id,
        string order_no,
        string order_date,
        string order_time,
        int  order_amount,
        string item_name,
        string mer_url,
        string result_url,
        string mer_order_param,
        string key,
        string _input_charset,
        string gateway
        )
    {

        //商户提交的支付请求中数字签名的原始签名摘要值按照以下格式生成（实际中用参数值替换格式中的‘？’，每个参数表达式之间用英文逗号分隔）
        //mer_id=?,order_date=?,order_no=?,order_time=?,order_amount=?,item_name=?,mer_url=?,result_url=?,key=?

        //key值是由商付宝平台发放给每个商户一个唯一的密值；
        //然后用MD5对摘要值进行操作得到对应的签名值

        //构造数组；
        string[] Oristr ={ 
                "mer_id="+mer_id, 
                "order_date=" + order_date, 
                "order_no=" + order_no, 
                "order_time=" + order_time, 
                "order_amount=" + order_amount , 
                //"item_count="+ item_count ,
                "item_name=" + item_name, 
                "mer_url=" + mer_url,
                "result_url="+result_url,
                  "key="+key 
                };

        //进行排序；
        //string[] Sortedstr = BubbleSort(Oristr);
        //构造待md5摘要字符串 ；

        StringBuilder prestr = new StringBuilder();

        for (int i = 0; i < Oristr.Length; i++)
        {
            if (i == Oristr.Length - 1)
            {
                prestr.Append(Oristr[i]);
            }
            else
            {
                prestr.Append(Oristr[i] + ",");//此处用逗号分割
            }
        }
        //prestr.Append(key);

        //生成Md5摘要；
        string sign = GetMD5Sign(prestr.ToString(), key);
        //string sign = GetMD5Sign(prestr.ToString(), key);
        //string sign = "yw9q84ywu2903wjr";

        //构造支付Url；
        char[] delimiterChars = { '=' };
        StringBuilder parameter = new StringBuilder();
        parameter.Append(gateway);
        for (int i = 0; i < Oristr.Length; i++)
        {
            //--原始 parameter.Append(Sortedstr[i].Split(delimiterChars)[0] + "=" + HttpUtility.UrlEncode(Sortedstr[i].Split(delimiterChars)[1]) + "&");
            //--修改
            //转换成URl 
            //byte[] url = HttpUtility.UrlEncodeToBytes(Sortedstr[i].Split(delimiterChars)[1]);
            string canshu = System.Web.HttpUtility.UrlDecode(HttpUtility.UrlEncode(Oristr[i].Split(delimiterChars)[1]));
            parameter.Append(Oristr[i].Split(delimiterChars)[0] + "=" + canshu + "&");
        }
        parameter.Append("sign=" + sign);

        //返回支付Url；
        return parameter.ToString();
    }

    /// <summary>
    /// %转换/
    /// </summary>
    /// <param name="byt"></param>
    /// <returns></returns>
    public static string UrlEncode(byte[] byt)
    {
        string desstr = "";
        for (int i = 0; i < byt.Length; i++)
        {
            desstr += "%";
            desstr += byt[i].ToString("X2");
        }
        return desstr;
    }

        //string UrlEncode(byte[] byt)
        //{
        //    string desstr = "";
        //    for (int i = 0; i < byt.Length; i++)
        //    {
        //        desstr += "%";
        //        desstr += byt[i].ToString("X2");
        //    }
        //    return desstr;
        //}


        ///支付宝的方法，供参考
        //public static string CreatUrl(
        //    string gateway, 
        //    string service, 
        //    string partner, 
        //    string sign_type,
        //    string out_trade_no,
        //    string subject, 
        //    string body,
        //    string total_fee, 
        //    string show_url, 
        //    string seller_email, 
        //    string key, 
        //    string return_url,
        //    string _input_charset,
        //    string notify_url
        //    )
        //{
        //    /// <summary>
        //    /// created by sunzhizhi 2006.5.21,sunzhizhi@msn.com。
        //    /// </summary>
        //    int i;
           
        //     //构造数组；
        //        string[] Oristr ={ 
        //        "service="+service, 
        //        "partner=" + partner, 
        //        "subject=" + subject, 
        //        "body=" + body, 
        //        "out_trade_no=" + out_trade_no, 
        //        "total_fee=" + total_fee, 
        //        "show_url=" + show_url,  
        //        "payment_type=1", 
        //        "seller_email=" + seller_email, 
        //        "notify_url=" + notify_url,
        //        "_input_charset="+_input_charset,          
        //        "return_url=" + return_url
        //        };
            
        //    //进行排序；
        //    string[] Sortedstr = BubbleSort(Oristr);


        //    //构造待md5摘要字符串 ；

        //    StringBuilder prestr = new StringBuilder();

        //    for (i = 0; i < Sortedstr.Length; i++)
        //    {
        //        if (i == Sortedstr.Length - 1)
        //        {
        //            prestr.Append(Sortedstr[i]);

        //        }
        //        else
        //        {

        //            prestr.Append(Sortedstr[i] + "&");
        //        }

        //    }

        //    prestr.Append(key);

        //    //生成Md5摘要；
        //    string sign = GetMD5(prestr.ToString(), _input_charset);

        //    //构造支付Url；
        //    char[] delimiterChars = { '='};
        //    StringBuilder parameter = new StringBuilder();
        //    parameter.Append(gateway);
        //    for (i = 0; i < Sortedstr.Length; i++)
        //    {

        //        parameter.Append(Sortedstr[i].Split(delimiterChars)[0] + "=" + HttpUtility.UrlEncode(Sortedstr[i].Split(delimiterChars)[1]) + "&");
        //    }

        //    parameter.Append("sign=" + sign + "&sign_type=" + sign_type);

        //    //返回支付Url；
        //    return parameter.ToString();

        //}
}
